package com.diana.common;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestSeckill {

    private Logger log = LoggerFactory.getLogger(TestSeckill.class);

    ThreadPoolExecutor pool = new ThreadPoolExecutor(10,100,60, TimeUnit.MICROSECONDS,new LinkedBlockingQueue<>());
    ThreadPoolExecutor pool2 = new ThreadPoolExecutor(10,100,60, TimeUnit.MICROSECONDS,new LinkedBlockingQueue<>());

    public void dopost(String productId,String userId){

        String host = "http://localhost:9001";
        String path = "/common/seckill";
        String mothed = "post";
        Map<String,String> headers = new HashMap<>();
        Map<String ,String> body = new HashMap<>();
        body.put("productId",productId);
        body.put("userId",userId);
        try {
            HttpResponse response = (HttpResponse) HttpUtils.doPost(host, path, mothed, headers, null, body);
            String res = EntityUtils.toString(response.getEntity());
            log.info(res);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

    }

    public void thread(){
        String [] userIds = new String[3000];
        String userId = null;
        for(int i = 0;i<3000;i++){
            int id = 10000+i;
            userId = "U"+id;
            userIds[i] = userId;
        }
        String productId = "P10001";
        for (int i=0;i<30;i++){
            /*try {
                Thread.sleep(500);
            }catch (Exception e){
                e.printStackTrace();
            }*/
            /*pool.execute(new Runnable() {
                @Override
                public void run() {
                    dopost(productId,userIds[ran.nextInt(userIds.length)]);
                }
            });*/
            new Thread(new Runnable() {
                @Override
                public void run() {
                    test1(productId,userIds);
                }
            }).start();
        }
    }

    public void test1(String productId,String[] userIds){
        Random ran = new Random();
        for(int i=0;i<100;i++){
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    dopost(productId,userIds[ran.nextInt(userIds.length)]);
                }
            });
        }
    }

    public static void main(String[] args) {
        TestSeckill tt = new TestSeckill();
        tt.thread();
    }
}
